/**
 * @Author: likang xie
 * @Date: 2019-11-27 10:37:44
 * @Usage: 初始化腾讯IM实例
 */
import config from "@/config";

// #ifdef H5
import TIM from 'tim-js-sdk';
import COS from "cos-js-sdk-v5";
// #endif

// #ifndef H5
import TIM from "tim-wx-sdk";
import COS from 'cos-wx-sdk-v5';
// #endif

import {
	infoImSign
} from "@/apis/app";

let tim = null; // 腾讯IM实例

let login = (userId, userSign) => {
	return new Promise((resolve, reject) => {
		tim
			.login({
				userID: userId,
				userSig: userSign
			})
			.then(res => {
				uni.hideLoading();

				console.log("登录成功: ", res);

				// SDK初始化完毕
				tim.on(TIM.EVENT.SDK_READY, function(event) {
					resolve();
					uni.setStorageSync("timUserSign", userSign);
				});
			})
			.catch(err => {
				uni.hideLoading();
				uni.setStorageSync("timUserSign", "");

				console.error("登录失败: ", err);
				reject();
			});
	});
};

export default () => {
	return new Promise((resolve, reject) => {
		// 用户未登录的情况下不初始化
		let userId = String(uni.getStorageSync("userInfo").id || "");
		if (!userId) return console.log("用户未登录，不进行初始化腾讯IM实例");

		// 用户签名
		let userSign = uni.getStorageSync("timUserSign") || "";

		// 创建实例
		tim = TIM.create({
			SDKAppID: config.timId
		});

		// 引入插件
		tim.registerPlugin({
			"cos-wx-sdk": COS
		});

		setTimeout(() => {
			// 登录
			if (userSign) {
				login(userId, userSign).then(() => {
					console.log("腾讯TM实例初始化成功: ", tim);
					resolve(tim);
				});
			} else {
				infoImSign()
					.then(res => {
						let {
							code,
							data
						} = res;

						if (code == 200) {
							login(userId, data.sign).then(() => {
								console.log("腾讯TM实例初始化成功: ", tim);
								resolve(tim);
							});
						} else {
							uni.setStorageSync("timUserSign", "");
						}
					})
					.catch(err => {
						uni.setStorageSync("timUserSign", "");
					});
			}
		}, 500);
	});
};
